{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Adadelta\n",
    ":label:`sec_adadelta`\n",
    "\n",
    "Adadelta is yet another variant of AdaGrad. The main difference lies in the fact that it decreases the amount by which the learning rate is adaptive to coordinates. Moreover, traditionally it referred to as not having a learning rate since it uses the amount of change itself as calibration for future change. The algorithm was proposed in :cite:`Zeiler.2012`. It is fairly straightforward, given the discussion of previous algorithms so far. \n",
    "\n",
    "## The Algorithm\n",
    "\n",
    "In a nutshell Adadelta uses two state variables, $\\mathbf{s}_t$ to store a leaky average of the second moment of the gradient and $\\Delta\\mathbf{x}_t$ to store a leaky average of the second moment of the change of parameters in the model itself. Note that we use the original notation and naming of the authors for compatibility with other publications and implementations (there is no other real reason why one should use different Greek variables to indicate a parameter serving the same purpose in momentum, Adagrad, RMSProp, and Adadelta). The parameter du jour is $\\rho$. We obtain the following leaky updates:\n",
    "\n",
    "$$\\begin{aligned}\n",
    "    \\mathbf{s}_t & = \\rho \\mathbf{s}_{t-1} + (1 - \\rho) \\mathbf{g}_t^2, \\\\\n",
    "    \\mathbf{g}_t' & = \\sqrt{\\frac{\\Delta\\mathbf{x}_{t-1} + \\epsilon}{\\mathbf{s}_t + \\epsilon}} \\odot \\mathbf{g}_t, \\\\\n",
    "    \\mathbf{x}_t  & = \\mathbf{x}_{t-1} - \\mathbf{g}_t', \\\\\n",
    "    \\Delta \\mathbf{x}_t & = \\rho \\Delta\\mathbf{x}_{t-1} + (1 - \\rho) \\mathbf{x}_t^2.\n",
    "\\end{aligned}$$\n",
    "\n",
    "The difference to before is that we perform updates with the rescaled gradient $\\mathbf{g}_t'$ which is computed by taking the ratio between the average squared rate of change and the average second moment of the gradient. The use of $\\mathbf{g}_t'$ is purely for notational convenience. In practice we can implement this algorithm without the need to use additional temporary space for $\\mathbf{g}_t'$. As before $\\eta$ is a parameter ensuring nontrivial numerical results, i.e., avoiding zero step size or infinite variance. Typically we set this to $\\eta = 10^{-5}$. \n",
    "\n",
    "## Implementation\n",
    "\n",
    "Adadelta needs to maintain two state variables for each variable, $\\mathbf{s}_t$ and $\\Delta\\mathbf{x}_t$. This yields the following implementation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/GradDescUtils.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/TrainingChapter11.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDList initAdadeltaStates(int featureDimension) {\n",
    "    NDManager manager = NDManager.newBaseManager();\n",
    "    NDArray sW = manager.zeros(new Shape(featureDimension, 1));\n",
    "    NDArray sB = manager.zeros(new Shape(1));\n",
    "    NDArray deltaW = manager.zeros(new Shape(featureDimension, 1));\n",
    "    NDArray deltaB = manager.zeros(new Shape(1));\n",
    "    return new NDList(sW, deltaW, sB, deltaB);\n",
    "}\n",
    "\n",
    "public class Optimization {\n",
    "    public static void adadelta(NDList params, NDList states, Map<String, Float> hyperparams) {\n",
    "        float rho = hyperparams.get(\"rho\");\n",
    "        float eps = (float) 1e-5;\n",
    "        for (int i = 0; i < params.size(); i++) {\n",
    "            NDArray param = params.get(i);\n",
    "            NDArray state = states.get(2 * i);\n",
    "            NDArray delta = states.get(2 * i + 1);\n",
    "            // Update parameter, state, and delta\n",
    "            // In-place updates with the '__'i methods (ex. muli)\n",
    "            // state = rho * state + (1 - rho) * param.gradient^2\n",
    "            state.muli(rho).addi(param.getGradient().square().mul(1 - rho));\n",
    "            // rescaledGradient = ((delta + eps)^(1/2) / (state + eps)^(1/2)) * param.gradient\n",
    "            NDArray rescaledGradient = delta.add(eps).sqrt()\n",
    "                .div(state.add(eps).sqrt()).mul(param.getGradient());\n",
    "            // param -= rescaledGradient\n",
    "            param.subi(rescaledGradient);\n",
    "            // delta = rho * delta + (1 - rho) * g^2\n",
    "            delta.muli(rho).addi(rescaledGradient.square().mul(1 - rho));\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 2
   },
   "source": [
    "Choosing $\\rho = 0.9$ amounts to a half-life time of 10 for each parameter update. This tends to work quite well. We get the following behavior.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "AirfoilRandomAccess airfoil = TrainingChapter11.getDataCh11(10, 1500);\n",
    "\n",
    "public TrainingChapter11.LossTime trainAdadelta(float rho, int numEpochs) throws IOException, TranslateException {\n",
    "    int featureDimension = airfoil.getColumnNames().size();\n",
    "    Map<String, Float> hyperparams = new HashMap<>();\n",
    "    hyperparams.put(\"rho\", rho);\n",
    "    return TrainingChapter11.trainCh11(Optimization::adadelta, \n",
    "                                       initAdadeltaStates(featureDimension), \n",
    "                                       hyperparams, airfoil, \n",
    "                                       featureDimension, numEpochs);\n",
    "}\n",
    "\n",
    "TrainingChapter11.LossTime lossTime = trainAdadelta(0.9f, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "As usual, for a concise implementation, we simply create an instance of `adadelta` from the `Optimizer` class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    },
    "origin_pos": 5,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "Optimizer adadelta = Optimizer.adadelta().optRho(0.9f).build();\n",
    "\n",
    "TrainingChapter11.trainConciseCh11(adadelta, airfoil, 2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## Summary\n",
    "\n",
    "* Adadelta has no learning rate parameter. Instead, it uses the rate of change in the parameters itself to adapt the learning rate. \n",
    "* Adadelta requires two state variables to store the second moments of gradient and the change in parameters. \n",
    "* Adadelta uses leaky averages to keep a running estimate of the appropriate statistics. \n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Adjust the value of $\\rho$. What happens?\n",
    "1. Show how to implement the algorithm without the use of $\\mathbf{g}_t'$. Why might this be a good idea?\n",
    "1. Is Adadelta really learning rate free? Could you find optimization problems that break Adadelta?\n",
    "1. Compare Adadelta to Adagrad and RMS prop to discuss their convergence behavior.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
